﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Remider.Entity;
using SQLiteHelper;

namespace Remider.Utility
{
    public class AppointmentStore
    {
        public static readonly List<Appointment> CurrentAppointments = new List<Appointment>();

        public static void GetLock()
        {
            Monitor.Enter(CurrentAppointments);
        }

        public static void ReleaseLock()
        {
            Monitor.Exit(CurrentAppointments);
        }

        public static void LoadAppointTask()
        {
            GetLock();
            CurrentAppointments.Clear();
            var sqLite = MySqLiteFactory.GetFromPool();
            var reader = sqLite.ExcuteReader("select * from appointment where isdelete!='Y'");

            while (reader.Read())
            {
                string title = reader.GetString(3);
                var appointment = new Appointment()
                {
                    Title = title,
                    AppointmentId = reader.GetInt32(0),
                    AppointmentType = reader.GetInt32(1),
                    ActionType = reader.GetInt32(2),
                    Content = reader.GetString(4),
                    IsDone = reader.GetString(5),
                    ScheduleDate = reader.GetDateTime(6),
                    LastRunDate = reader.IsDBNull(7) ? (DateTime?)null : reader.GetDateTime(7),
                    NextRunDate = reader.GetDateTime(8),
                    LoopInt = reader.GetInt32(9),
                    IsDelete = reader.GetString(10)
                };
                CurrentAppointments.Add(appointment);
            }
            reader.Close();

            foreach (var appointment in CurrentAppointments)
            {
                if (appointment.NextRunDate < DateTime.Now && appointment.IsDone == "N" && appointment.LoopInt > 0)
                {
                    while (appointment.NextRunDate < DateTime.Now)
                    {
                        appointment.NextRunDate = appointment.NextRunDate.AddMinutes(appointment.LoopInt);
                    }
                    appointment.UpdateNexeRunTime(appointment.NextRunDate);
                }
            }

            CurrentAppointments.Sort((x, y) => x.AppointmentId - y.AppointmentId);
            ReleaseLock();
        }
    }
}
